package org.lql.chaos.rocketmq.callback;

import io.micrometer.core.instrument.Metrics;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author: liangqinglong
 * @date: 2025-08-16 21:14
 * @description:
 **/
public class MonitoredSendCallback implements SendCallback {

	private static final Logger log = LoggerFactory.getLogger(MonitoredSendCallback.class);
	private final String topic;
	private final long startTime;

	public MonitoredSendCallback(String topic) {
		this.topic = topic;
		this.startTime = System.currentTimeMillis();
	}

	@Override
	public void onSuccess(SendResult sendResult) {
		long cost = System.currentTimeMillis() - startTime;
		log.info("消息发送成功，Topic: {}，耗时: {}ms", topic, cost);
		// 上报监控指标
		Metrics.counter("rocketmq.send.success", "topic", topic).increment();
		Metrics.timer("rocketmq.send.latency", "topic", topic).record(cost, TimeUnit.MILLISECONDS);
	}

	@Override
	public void onException(Throwable throwable) {
		long cost = System.currentTimeMillis() - startTime;
		log.error("消息发送失败，Topic: {}，耗时: {}ms", topic, cost, throwable);
		// 上报失败监控指标
		Metrics.counter("rocketmq.send.failure", "topic", topic).increment();
	}
}